package com.wkh.project.driver.service.impl;

import com.wkh.project.common.result.Result;
import com.wkh.project.common.result.ResultCodeEnum;
import com.wkh.project.driver.client.CiFeignClient;
import com.wkh.project.driver.service.FileService;
import com.wkh.project.driver.service.MonitorService;
import com.wkh.project.model.entity.order.OrderMonitor;
import com.wkh.project.model.entity.order.OrderMonitorRecord;
import com.wkh.project.model.form.order.OrderMonitorForm;
import com.wkh.project.model.vo.order.TextAuditingVo;
import com.wkh.project.order.client.OrderMonitorFeignClient;
import com.wkh.project.service.execption.GuiguException;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

@Slf4j
@Service
@SuppressWarnings({"unchecked", "rawtypes"})
public class MonitorServiceImpl implements MonitorService {

    @Resource
    private OrderMonitorFeignClient orderMonitorFeignClient;
    @Resource
    private FileService fileService;
    @Resource
    private CiFeignClient ciFeignClient;

    @Override
    public Boolean upload(MultipartFile file, OrderMonitorForm orderMonitorForm) {
        //上传对话文件
        String url = fileService.upload(file);
        log.info("upload: {}", url);

        //保存订单监控记录表
        OrderMonitorRecord orderMonitorRecord = new OrderMonitorRecord();
        orderMonitorRecord.setOrderId(orderMonitorForm.getOrderId());
        orderMonitorRecord.setFileUrl(url);
        orderMonitorRecord.setContent(orderMonitorForm.getContent());   
        //记录审核结果
        TextAuditingVo textAuditingVo = ciFeignClient.textAuditing(orderMonitorForm.getContent()).getData();
        orderMonitorRecord.setResult(textAuditingVo.getResult());
        orderMonitorRecord.setKeywords(textAuditingVo.getKeywords());
        orderMonitorFeignClient.saveMonitorRecord(orderMonitorRecord);

        //更新订单监控统计
        Result<OrderMonitor> orderMonitorResult = orderMonitorFeignClient.getOrderMonitor(orderMonitorForm.getOrderId());
        if (orderMonitorResult.getCode() != 200){
            throw new GuiguException(ResultCodeEnum.FEIGN_FAIL);
        }
        OrderMonitor orderMonitor = orderMonitorResult.getData();
        //文件数量+1
        orderMonitor.setFileNum(orderMonitor.getFileNum() + 1);
        if ("1".equals(orderMonitorRecord.getResult()) || "2".equals(orderMonitorRecord.getResult())) {
            int auditNum = orderMonitor.getAuditNum() + 1;
            orderMonitor.setAuditNum(auditNum);
        }
        Result<Boolean> updated = orderMonitorFeignClient.updateOrderMonitor(orderMonitor);
        if (updated.getCode() != 200){
            throw new GuiguException(ResultCodeEnum.FEIGN_FAIL);
        }
        return updated.getData();
    }
}
